<script lang="ts" setup>

import {ref} from 'vue'
import {contrimGetListSerive,contrimRedownSerive,contrimDeleteSerive,contrimUpdateClickSerive} from '@/api/contrim.js'

import { operationLogAddSerive } from '@/api/operationlog.js';
import uploadContrim from './component/uploadContrim.vue'
// 添加下载进度状态
const downloadProgress = ref(0);
const downloading = ref(false);
const params = ref({
    pagenum:1,
    pagesize:10,
    username:null
})
const userList = ref([])
const total = ref(0)
const uploadContrimRef = ref()
const getUserList = async()=>{
   const res =  await contrimGetListSerive(params.value)
   userList.value = res.data.data.result
   total.value = res.data.data.total
}
getUserList()
const handleSizeChange = async(val:number)=>{
   params.value.pagenum = 1
   params.value.pagesize = val
   getUserList()

}  
const handleCurrentChange =async (val:number)=>{
   params.value.pagenum = val
   getUserList()

}

const Search =async ()=>{
  getUserList()
    await  operationLogAddSerive({
    operation_type:'搜索操作',
    details:`在合同管理模块进行了搜索操作`,
    level:2
  })
  ElMessage.success('搜索成功！')
}
const reSet = async()=>{
  params.value.username = null
  getUserList()
      await  operationLogAddSerive({
    operation_type:'重置操作',
    details:`在合同管理模块进行了重置操作`,
    level:2
  })
  ElMessage.success('重置成功！')
}
const deleteAll = async(row:any)=>{
  await contrimDeleteSerive(row.file_id)
        await  operationLogAddSerive({
    operation_type:'清空合同管理操作',
    details:`在合同管理模块进行了合同管理操作`,
    level:1
  })
  getUserList()
  ElMessage.success('删除合同管理成功！')
}

const redown = async(row:any)=>{
     try {
    downloading.value = true;
    downloadProgress.value = 0;
    
    const res = await contrimRedownSerive(row.file_id, (percent:any) => {
      downloadProgress.value = percent;
    });
    
    // 创建下载链接
    const blob = new Blob([res.data], { 
      type: res.headers['content-type'] || 'application/octet-stream'
    });
    
    const downloadUrl = window.URL.createObjectURL(blob);
    const contentDisposition = res.headers['content-disposition'];
    const fileName = contentDisposition 
      ? decodeURIComponent(contentDisposition.split('filename=')[1])
      : row.original_name;
    
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = fileName || '下载文件';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(downloadUrl);
    await contrimUpdateClickSerive(row.file_id)
    getUserList()
    ElMessage.success('下载成功！');
    
  } catch (error) {
    console.error('下载失败:', error);
    ElMessage.error('下载失败，请重试');
  } finally {
    downloading.value = false;
  }
}
// 类型定义
type UnitKeys = 'Bytes' | 'KB' | 'MB' | 'GB';

const unitMap: Record<UnitKeys, string> = {
  Bytes: '字节',
  KB: 'KB',
  MB: 'MB',
  GB: 'GB'
};

// 格式化方法
const formatFileSize=(bytes: number): string=> {
  if (bytes === 0) return '0 字节';
  
  const units: UnitKeys[] = ['Bytes', 'KB', 'MB', 'GB'];
  const unitSteps = [1, 1024, 1024**2, 1024**3];
  
  const unitLevel = unitSteps.findIndex(step => bytes < step * 1024);
  const value = bytes / unitSteps[unitLevel];
  
  // 类型安全的单位访问
  const unitKey = units[unitLevel] as UnitKeys;
  
  return unitLevel === 0
    ? `${value} ${unitMap.Bytes}`
    : `${value.toFixed(2)} ${unitMap[unitKey]}`;
}

const uploadText = ()=>{
    uploadContrimRef.value.open()
}
const onSuccess = ()=>{
  getUserList()
}
</script>

<template>
   <div class="wrapped">
     <el-card>
       <div class="wrapped-content">
          <div class="select">
            <div class="input">
            <el-form-item>
                <el-input placeholder="输入账号进行搜索"  v-model="params.username" suffix-icon="Search"/>
            </el-form-item>
             <el-form-item>
                <el-button type="primary" @click="Search">搜索</el-button>
            </el-form-item>
            <el-form-item>
               <el-button type="primary" @click="reSet">重置</el-button>
            </el-form-item>
            </div>
            <div class="btn">
                <el-button type="primary" @click="uploadText">上传文件</el-button>

            </div>
          </div>
             <el-table :data="userList" border  style="width: 100%">
             <el-table-column align="center" type="index" label="序号" width="100" />
             <el-table-column align="center" prop="original_name" label="文件名称" width="150" />
              <el-table-column align="center" prop="size" label="文件大小" width="150" >
                <template #default="{row}">
                 {{ formatFileSize(row.size) }}
                </template>
              </el-table-column>
             <el-table-column align="center" prop="nickname" label="上传用户" width="150" />
              <el-table-column align="center" prop="click_number" label="下载次数" width="200" />
             <el-table-column align="center" prop="created_time" label="上传时间" width="200" >
                <template #default="{row}">
                  {{row.created_time?.slice(0,16)}}
                </template>
             </el-table-column>
             <el-table-column align="center"   fixed="right" label="操作" >
                <template #default="{row}">
                    <el-button  type="primary" size="small" @click="redown(row)">
                          下载
                    </el-button>
                    <el-button  type="primary" size="small" @click="deleteAll(row)">删除</el-button>
                </template>
             </el-table-column>
             <template #empty>
            <el-empty description="暂无数据" />
            </template>
             </el-table>       
            <el-pagination
                v-model:current-page="params.pagenum"
                v-model:page-size="params.pagesize"
                :page-sizes="[5, 10, 20, 30]"
                :background="true"
                layout="jumper,total, sizes, prev, pager, next "
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                style="float: right; margin: 10px 0;"

            />

   </div> 
     </el-card>
     <uploadContrim ref="uploadContrimRef" @success="onSuccess" />
   </div>
</template>

<style lang="scss" scoped>
.wrapped{
.wrapped-content{
    height: 600px;
    padding: 0 10px;
    .select{
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
        .input{
            display: flex;
            justify-content: flex-start;
            .el-input,.el-select{
              width: 200px;
              margin-right: 10px;
            }
            .el-button{
                margin-right:10px ;
            }
        }

    }
}
}
</style>